package com.jiadakeji.ppm.common.utils;


import com.jiadakeji.ppm.common.mapper.JsonMapper;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderNotifyResponse;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderRequest;
import com.jiadakeji.ppm.modules.weixin.entity.WechatUnifiedorderResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Map;

public class WechatUtils {


	private static Logger logger = LoggerFactory.getLogger(WechatUtils.class);

	public static final String appid = "wxed8e514891b578b9";
	public static final String secret = "2431fa1d9ada8b19dacebb0d3916ac1e";
	public static final String grant_type = "authorization_code";

	public static final String mch_id = "1480435952";
	public static final String wechat_key = "abcdefghijklmnopqrstuvwxyz123456";

	public static final String sub_appid = "wx90877f1195251d0c";
	public static final String sub_secret = "25db22c79fa92b820d82cd655308e64a";
	public static final String sub_mch_id = "1548217901";

	private static final String URL = "https://ppm.jiadakeji.cn";



	public static final String feeReceiveNotifyUrl = URL+"/api/v1/feeReceive/wechatNotify";
	public static final String rechargeNotifyUrl = URL+"/api/v1/movie/cinemaPlanOrder/wechatNotify";
	public static final String RefundNotifyUrl = URL+"/api/v1/feeReceiver/refund/wechatNotify";

	@SuppressWarnings("unchecked")
	public static Map<String, String> jscode2session(String code){
		String url = "https://api.weixin.qq.com/sns/jscode2session";
		String param = "appid=" + sub_appid + "&secret=" + sub_secret + "&js_code=" + code + "&grant_type=" + grant_type;
		String wxResult = UrlUtils.sendGet(url, param);
		return (Map<String, String>) JsonMapper.fromJsonString(wxResult, Map.class);
	}


//	public static void main(String[] args) {
//
//		jscode2session("0131CZxb1l2Wwu0grNxb1HPdyb11CZxv");
//
//
//	}


	/**
	 *  请求统一下单
	 *  URL： https://api.mch.weixin.qq.com/pay/unifiedorder
	 */
	public static String unifiedorder(String request){

		String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		String wxResult = UrlUtils.HttpsRequest(url,"POST",request);
		return wxResult;

	}

	/**
	 *  请求退款
	 *  URL： https://api.mch.weixin.qq.com/secapi/pay/refund
	 */
	public static String refund(String request){
		String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		try {
			String wxResult = UrlUtils.PostWithCert(url,request,true);
			return wxResult;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成微信需要的 xml格式
	 * 并且生成签名
	 * @param request
	 * @return
	 */
	public static String  generateRequestXml(WechatUnifiedorderRequest request ){

		String xml = null;
		try {
			String temp = ObjectSortAscll.getSortMap(request);
			logger.info("没有连接key:"+temp);
			temp = temp+"&key="+wechat_key;//TODO key需要使用配置文件
			/*temp = temp+"&key="+PropertiesLoader.getValueMarketking("wechatKey");//使用配置文件*/
			logger.info("连接key:"+temp);
			String sign = MD5Utils.parseStrToMd5U32(temp);
			logger.info("签名sign:"+sign);
			request.setSign(sign);
			xml = XmlUtils.objectToXml(request);
		}catch (Exception e){

		}finally {
			return  xml;
		}
	}

/*
	public static String  generateRequestXml(WechatPayRefundRequest request ){
		String xml = null;
		try {
			String temp = ObjectSortAscll.getSortMap(request);
			logger.info("没有连接key:"+temp);
			temp = temp+"&key="+wechat_key;//TODO key需要使用配置文件
			logger.info("连接key:"+temp);
			String sign = MD5Utils.parseStrToMd5U32(temp);
			logger.info("签名sign:"+sign);
			request.setSign(sign);
			xml = XmlUtils.objectToXml(request);
			logger.info(xml);
		}catch (Exception e){

		}finally {
			return  xml;
		}
	}*/

	/**
	 *  微信统一下单接口响应转化为对象
	 * @param xml
	 * @return
	 */
	public static WechatUnifiedorderResponse responseXmlToObject(String xml){

		WechatUnifiedorderResponse response = (WechatUnifiedorderResponse) XmlUtils.xmlToObject(WechatUnifiedorderResponse.class,xml);

		return  response;

	}


	/**
	 * 解析http发送的信息
	 * @param request
	 * @return
	 */
	public static String readInfoFromHttpRequest(HttpServletRequest request){
		StringBuffer xmlstr = new StringBuffer();
		try {
			BufferedReader reader = request.getReader();
			String line = null;
			while((line = reader.readLine()) != null){
				xmlstr.append(line);
			}
			logger.info("统一下单微信回调参数："+xmlstr.toString());

		}catch (Exception e){
			logger.error("微信回调解析失败，异常信息为:"+e.getMessage());

		}finally {
			return  xmlstr.toString();
		}

	}

	public static String  checkNotifySign(String xml, HttpServletResponse servletResponse){
		String sign = null;
		WechatUnifiedorderNotifyResponse wechatResponse = new WechatUnifiedorderNotifyResponse();
		try {
			try {
				Map<String,String> notifyRequest = XmlUtils.xmlToMap(xml);
				String temp = ObjectSortAscll.getSortMap(notifyRequest);
				temp = temp.replaceAll("sign.+?&","");//取消sign 微信传回的sign不能参与签名
				temp +="&key="+ WechatUtils.wechat_key;//使用配置文件
				logger.info("验证微信回调参数加key:"+temp);
				sign = MD5Utils.parseStrToMd5U32(temp);
				logger.info("签名:"+sign);
			}catch (Exception e ){
				logger.error("统一下单签名 生成生成签名错误");
				logger.error(e.getMessage());
				wechatResponse.setReturn_code("FAIL");
				servletResponse.getWriter().write(XmlUtils.jacksonObjToXml(wechatResponse));
				return null;
			}

		}catch (Exception e){
			logger.error("验证参数出现异常:"+e.getMessage());
		}finally {
			return sign;
		}

	}

}
